package per.sen.shopping.infrastructure.utils;

import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import io.vertx.mutiny.sqlclient.Row;
import per.sen.shopping.infrastructure.common.exception.BaseException;
import per.sen.shopping.infrastructure.common.response.HttpStatus;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @Describe: RowSet转化实体工具类(数据库查询结果转化实体)
 * @Author: LYS
 * @Date: 2024/6/15 23:09
 */
public class RowToClazzUtil {
    private static final Mapper dozerMapper = DozerBeanMapperBuilder.buildDefault();
    private static final String  SERIALVERSIONUID = "serialVersionUID";

    public static <T> T convert(Row row ,Class<T> entityType) throws BaseException {
        T entityInstance;
        try {
            entityInstance  = entityType.getDeclaredConstructor().newInstance();
            Class<?> declaringClass = entityType.getDeclaringClass();
            Field[] declaredFields = entityType.getDeclaredFields();
            for (Field field : declaredFields) {

                String fieldName = field.getName();
                if(SERIALVERSIONUID.equals(fieldName) || fieldName.contains("$$_hibernate")){
                    continue;
                }
                Class<?> fieldType = field.getType();
                Object o;
                if(fieldType.getName().equals("java.util.Date")){
                    LocalDateTime localDateTime = row.getLocalDateTime(fieldName);
                    if(localDateTime != null){
                        o = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
                    }else{
                        o = null;
                    }
                }else{
                     o = row.get(fieldType, fieldName);
                }
                Field declaredField = entityType.getDeclaredField(fieldName);
                declaredField.setAccessible(true);
                declaredField.set(entityInstance,o);
            }
        } catch (Exception e) {
            throw new BaseException(HttpStatus.INTERNAL_SERVER_ERROR.getCode(),null,"manager",e.getMessage());
        }
        return entityInstance;
    }

}
